package com.aiyige.page.selectregion;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.eventbus.EventPickRegion;
import com.aiyige.base.eventbus.EventSelectRegion;
import com.aiyige.location.LocationUtil;
import com.aiyige.location.model.RegionData;
import com.aiyige.page.selectregion.adapter.SearchResultAdapter;
import com.aiyige.page.selectregion.adapter.SelectRegionPagerAdapter;
import com.aiyige.page.selectregion.model.RegionItem;
import com.aiyige.utils.DummyDataUtil;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flyco.tablayout.SlidingTabLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = ARouterConfig.SelectRegionPage)
public class SelectRegionPage extends AppCompatActivity {
    private static final int HANDLE_SEARCH = 1;
    @BindView(R.id.backBtn)
    ImageView backBtn;
    @BindView(R.id.hintLayout)
    LinearLayout hintLayout;
    @BindView(R.id.searchIcon)
    ImageView searchIcon;
    @BindView(R.id.inputEt)
    EditText inputEt;
    @BindView(R.id.searchBox)
    FrameLayout searchBox;
    @BindView(R.id.cancelSearchBtn)
    Button cancelSearchBtn;
    @BindView(R.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R.id.regionVp)
    ViewPager regionVp;
    @BindView(R.id.searchResultRv)
    RecyclerView searchResultRv;
    @BindView(R.id.searchResultLayout)
    LinearLayout searchResultLayout;
    List<RegionItem> regionItemList = new LinkedList<>();
    HandlerThread searchHandlerThread;
    Handler searchHandler;
    Handler mainHandler;
    SearchResultAdapter searchResultAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_select_region);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        mainHandler = new Handler(Looper.getMainLooper());
        searchHandlerThread = new HandlerThread("RegionSearchThread");
        searchHandlerThread.start();
        searchHandler = new Handler(searchHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HANDLE_SEARCH:
                        String searchStr = (String) msg.obj;
                        final List<RegionItem> hitRegeionItemList = new LinkedList<>();
                        if (!TextUtils.isEmpty(searchStr)) {
                            for (RegionItem item : regionItemList) {
                                if (item.getFullName().contains(searchStr)) {
                                    hitRegeionItemList.add(item);
                                }
                            }
                        }
                        mainHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                searchResultAdapter.setNewData(hitRegeionItemList);
                            }
                        });
                        break;
                    default:
                        break;
                }
            }
        };
        regionVp.setAdapter(new SelectRegionPagerAdapter(getSupportFragmentManager()));
        tabLayout.setViewPager(regionVp);
        inputEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    searchIcon.setVisibility(View.VISIBLE);
                    hintLayout.setVisibility(View.INVISIBLE);
                } else if (inputEt.getText().length() == 0) {
                    searchIcon.setVisibility(View.INVISIBLE);
                    hintLayout.setVisibility(View.VISIBLE);
                }
            }
        });
        inputEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() != 0) {
                    searchResultLayout.setVisibility(View.VISIBLE);
                    cancelSearchBtn.setVisibility(View.VISIBLE);
                }
                doSearch(s.toString());
            }
        });
        searchResultAdapter = new SearchResultAdapter();
        searchResultRv.setLayoutManager(new LinearLayoutManager(this));
        searchResultRv.setAdapter(searchResultAdapter);
        searchResultAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (searchResultAdapter.getItem(position).getItemType() == RegionItem.TYPE_DATA) {
                    //LocationUtil.setCurrentUserSelectRegion(new RegionData(searchResultAdapter.getItem(position).getName(), searchResultAdapter.getItem(position).getFullName()));
                    EventBus.getDefault().post(new EventPickRegion(new RegionData(searchResultAdapter.getItem(position).getName(), searchResultAdapter.getItem(position).getFullName(),searchResultAdapter.getItem(position).getId())));
                    finish();
                }
            }
        });
        loadData();
    }

    private void doSearch(String searchStr) {
        Message msg = Message.obtain();
        msg.what = HANDLE_SEARCH;
        msg.obj = searchStr;
        searchHandler.removeMessages(HANDLE_SEARCH);
        searchHandler.sendMessage(msg);
    }

    private void loadData() {
        new AsyncTask() {

            @Override
            protected Object doInBackground(Object[] params) {
                return DummyDataUtil.getChinaRegionData();
            }

            @Override
            protected void onPostExecute(Object o) {
                if (o != null) {
                    regionItemList = (List<RegionItem>) o;
                }
            }
        }.execute();
    }

    @OnClick({R.id.backBtn, R.id.cancelSearchBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backBtn:
                finish();
                overridePendingTransition(R.anim.activity_still, R.anim.activity_slide_out_bottom);
                break;
            case R.id.cancelSearchBtn: {
                inputEt.setText("");
                inputEt.clearFocus();
                cancelSearchBtn.setVisibility(View.INVISIBLE);
                searchResultLayout.setVisibility(View.INVISIBLE);
                break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        searchHandlerThread.quit();
        super.onDestroy();
    }


}
